package com.axsoft.train;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.util.Log;

/*
 * This class implements some Http-related routines
 * 
 */
class MiscUtils {
	
	/*
	 * Precess http GET request
	 */
	public static String getRequest(String url)
	{
		if (url == null) {
			return null; // FIXME: DO NOT return NULL! Throw exception!
		}
		
		String html = null;
		HttpClient httpClient = null;
		HttpGet httpGet = null;
		ResponseHandler<String> responseHandler = null;
		
		try	{
			httpClient = new DefaultHttpClient();
			httpGet = new HttpGet(url);
			
			responseHandler = new ResponseHandler<String>() {
				@Override
				public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
					StatusLine statusLine = response.getStatusLine();
					
					if (statusLine.getStatusCode() >= 300) {
						throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
					}
					
					HttpEntity entity = response.getEntity();
					return ((entity == null) ? null : EntityUtils.toString(entity, "UTF-8"));
				}
			};
			
			html = httpClient.execute(httpGet, responseHandler);
			httpClient.getConnectionManager().shutdown();
		} catch (Exception e) {
			Log.e("HttpUtils.getRequest", e.toString());
			return null;
		}
		
		return html;		
	}
	
	
	/*
	 * Gets train list for the given directions
	 */
	public static List<Train> getSchedule(String direction, String from, String to, boolean nearest) {
		if (from == null || to == null) {
			return null;	// FIXME: DO NOT return Null - throw exception!
		}
		
		List<Train> trains = null;
		InputStreamReader is = null;
	
		if (! nearest) {
			is = CacheManager.getScheduleFromCache(from, to);
		}
		
		// If there's no cache record - put it to the cache
		if (is == null)	{
			String url = Constants.URL_SUBURBAN_SEARCH + "station_from=" + from + "&station_to=" + to + "&direction=" + direction;
			
			if (! nearest) {
				url += "&mode=all";
			}
			
			String html = getRequest(url);
			
			if (! CacheManager.putScheduleToCache(from, to, html)) {
				return null; // FIXME
			}
		}
		
		is = CacheManager.getScheduleFromCache(from, to);
		
		if (is != null) {
			trains = Train.trainsFromCache(is, nearest);
		}
		
		return trains;
	}
	
	
	/*
	 * Opens file for read
	 * 
	 * @param fileName
	 */
	public static BufferedReader openFileForRead(String fileName) {
		try	{
			FileInputStream is = new FileInputStream(fileName);
			return new BufferedReader(new InputStreamReader(is, "utf8"), 8192);
		} catch (Exception e) {
			Log.e("HttpUtils.openFileForRead", e.toString());
			return null; // Fucking fucking fucking BAD code!
		}
	}
	
}